<template>
  <div class="app-container">
    <el-row>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm el-form-bottom">
        <el-divider content-position="left"><legend class="divider-line">分类编辑</legend></el-divider>
        <el-col :span="8">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="ruleForm.name" minlength="2" maxlength="20"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="16">
          <el-form-item label="权重" prop="sort">
            <el-input-number v-model="ruleForm.sort" :min="0" :max="99" :step="1" step-strictly></el-input-number>
            <span class="form-word-hint">权重值越大，显示越靠前</span>
          </el-form-item>
        </el-col>

        <el-col :span="16">
          <el-form-item label="上级分类">
            <span>{{ pathNames }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="this.pathNumber == 2">
          <el-form-item label="关联类型" prop="typeName">
            <el-button type="warning" @click.prevent="chooseType" icon="el-icon-search">选择</el-button>
            <span class="form-word-hint">类型只能选择不能输入</span>
            <el-input v-model="ruleForm.typeName" readonly style="display: none"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="this.pathNumber == 2">
          <el-form-item label="已选类型">
            <el-input v-model="ruleForm.typeName" readonly></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="16" v-if="this.pathNumber == 2">
          <el-form-item label="分佣比例" prop="scaling">
            <el-input-number v-model="ruleForm.scaling" :precision="3" :min="0" :step="0.001" step-strictly></el-input-number>
            <span class="form-word-hint">分佣比例是平台按照商家的销售总金额就行抽佣</span>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="this.pathNumber == 2">
          <el-form-item label="是否推荐" prop="isTop">
            <el-radio-group v-model="ruleForm.isTop">
              <el-radio v-for="item in statesList" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="16" v-if="this.pathNumber == 2">
          <el-form-item label="手机端图片">
            <el-upload
              class="avatar-uploader"
              :action="$imageUrl + '/uploadFileImage'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.image" :src="$imagePath + ruleForm.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <span class="form-word-hint">图片不能超过300KB，长和宽的比例是1：1</span>
          </el-form-item>
        </el-col>

        <el-col :span="16" v-if="pathNumber == 0">
          <el-form-item label="顶部图片">
            <el-upload
              class="avatar-uploader"
              :action="$imageUrl + '/uploadFileImage'"
              :show-file-list="false"
              :on-success="handleTopImageSuccess"
              :before-upload="beforeTopImageUpload">
              <img v-if="ruleForm.imageTop" :src="$imagePath + ruleForm.imageTop" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <span class="form-word-hint">顶部图片不能超过200KB，图片建议像素（或保持该比例）：宽720，高350</span>
          </el-form-item>
        </el-col>
      </el-form>
      <div class="fixed-bottom-20">
        <el-button type="primary" @click="submitForm('ruleForm')">立即提交</el-button>
        <el-button type="success" @click="back">返回</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-row>

    <el-dialog title="选择类型" destroy-on-close :visible.sync="dialogFormVisible">
      <el-table
        ref="multipleTable"
        :data="typeList"
        border
        fit
        height="350"
        style="width: 100%"
        highlight-current-row
        @current-change="handleCurrentChange">
        <el-table-column width="100" label="类型名称" prop="name"></el-table-column>
        <el-table-column width="100" label="关联规格" prop="normNames"></el-table-column>
        <el-table-column show-overflow-tooltip label="关联品牌" prop="brandNames"></el-table-column>
        <el-table-column width="100" prop="sort" label="权重"></el-table-column>
        <el-table-column width="100" label="创建人" prop="createUser"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateTypeData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { uploadFileImage, getCodeManager, codeToArray } from "@/api/all";
import { updateCate, getTypeList, editCate } from "@/api/product";
import { Message } from "element-ui";
export default {
  name: "cateEdit",
  data() {
    return {
      cateId: "",
      dialogFormVisible: false,
      multipleSelection: [],
      typeList: [],
      statesList: [],
      pathNames: "",
      pathNumber: 0,
      ruleForm: {
        name: "",
        sort: "",
        typeName: "",
        productTypeId: "",
        scaling: "0",
        image: "",
        imageFilePath: "",
        imageTop: "",
        isTop: "1",
      },
      rules: {
        name: [
          { required: true, message: "分类名称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "分类名称长度为2-20个字符",
            trigger: "blur",
          },
        ],
        sort: [{ required: true, message: "请输入权重", trigger: "blur" }],
        typeName: [{ required: true, message: "请选择关联类型", trigger: "blur" }],
        scaling: [{ required: true, message: "请输入分佣比例", trigger: "blur" }],
        isTop: [{ required: true, message: "是否推荐必选", trigger: "change" }],
      },
    };
  },
  created() {
    this.cateId = this.$route.query.id;
    this.getData(this.cateId);
    getCodeManager("YES_NO", () => {
      this.statesList = codeToArray("YES_NO");
    });
  },
  methods: {
    getData(id) {
      editCate({ id: id }).then((res) => {
        console.log(res.data.data);
        this.ruleForm = res.data.data.cate;
        this.ruleForm.typeName = res.data.data.typeName;
        if (!res.data.data.cate.isTop) this.ruleForm.isTop = "" + 0;
        this.ruleForm.isTop = "" + res.data.data.cate.isTop;
        this.pathNames = res.data.data.pathNames;
        this.pathNumber = res.data.data.pathNumber;
      });
    },
    handleCurrentChange(val) {
      // 选中类型行信息
      this.multipleSelection = val;
    },
    checkRow(data) {
      data.map((item) => {
        if (this.ruleForm.productTypeId == item.id) {
          this.toggleSelection(item, true);
        }
      });
    },
    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.multipleTable && this.$refs.multipleTable.setCurrentRow(row, select);
        });
      }
    },
    chooseType() {
      // 选择关联类型
      this.dialogFormVisible = true;
      getTypeList().then((res) => {
        this.typeList = res.data.rows;
        this.checkRow(res.data.rows);
      });
    },
    updateTypeData() {
      //  确认关联类型
      this.ruleForm.typeName = this.multipleSelection.name;
      this.ruleForm.productTypeId = this.multipleSelection.id;
      this.dialogFormVisible = false;
    },
    // 上传顶部图片
    handleTopImageSuccess(res, file) {
      const formData = new FormData();
      formData.append("type", "brand");
      formData.append("imageFile", file.raw);
      uploadFileImage(formData).then((result) => {
        if (result.data.success) {
          this.ruleForm.imageTop = result.data.data;
          this.$forceUpdate();
        }
      });
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      const formData = new FormData();
      formData.append("type", "brand");
      formData.append("imageFile", file.raw);
      uploadFileImage(formData).then((result) => {
        if (result.data.success) {
          this.ruleForm.image = result.data.data;
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 300 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 300KB!");
      }
      return isJPG && isLt2M;
    },
    beforeTopImageUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 200 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 200KB!");
      }
      return isJPG && isLt2M;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateCate(this.ruleForm).then((res) => {
            if (!res.data.success) {
              Message.error(res.data.message);
              return;
            }
            Message.success("操作成功");
            history.back();
          });
        }
      });
    },
    resetForm(formName) {
      this.getData(this.cateId);
    },
    back() {
      history.back();
    },
  },
};
</script>
<style scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/ [class*="el-col-"] {
  float: none;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  height: 150px;
  display: block;
}

.el-select {
  margin-right: 10px;
}
</style>
